import React, { useState, useEffect } from "react";
import axios from "../../model/User";
import {
  Input,
  Select,
  DatePicker,
  Space,
  Button,
  Table,
  Radio,
  Divider,
  message,
  Tag,
  Switch,
  Modal,
} from "antd";
const { RangePicker } = DatePicker;



export default function Search(props:any) {
  let [list, setlist] = useState<any>([]);
  let [keywords, setkeywords] = useState<any>("");
  useEffect(() => {
    initList();
  }, []);
  const success = () => {
    message.success('删除成功！');
  };
  
  const error = () => {
    message.error('删除失败！');
  };
  let del=(id:any)=>{
    axios.del(id);
    success();
    initList();
  }

  let viptypeaxios = async (num: Number) => {
    axios.query({ viptype: num }).then((res) => {
      let arr = res.data;
      // console.log(res.data);
      let arrs = [];
      for (let i = 0; i < arr.length; i++) {
        let obj = {
          key: i,
          username: (
            <>
              <div style={{ float: "left" }}>
                <img src={arr[i].touxiang}></img>
              </div>
              <div style={{ float: "right" }}>
                <div>{arr[i].username}</div>
                <div>{arr[i].tel}</div>
              </div>
            </>
          ),
          viptype:
            arr[i].viptype == 1
              ? "普通会员"
              : arr[i].viptype == 2
              ? "金卡会员"
              : arr[i].viptype == 3
              ? "银卡会员"
              : arr[i].viptype == 4
              ? "白金会员"
              : "钛金会员",
          tags: arr[i].tags,
          orderNum: arr[i].orderNum,
          orderAmount: arr[i].orderAmount,
          state: (
            <Switch
              defaultChecked
              onChange={() => {
                onChangeUser(arr[i].state, arr[i].id);
              }}
              checked={arr[i].state}
            />
          ),
          registerTime: arr[i].registerTime,
          operation: (
            <>
              <Space>
                <Button onClick={()=>{
                  props.history.push("/system/user/userdetail/"+arr[i].id)
                }}>用户详情</Button>
                {/* <Button onClick={()=>{
                  props.history.push("/system/user/useredit/"+arr[i].id)
                }}>编辑用户</Button> */}
                <Button onClick={()=>{
                del(arr[i].id)
              }}>删除</Button>
              </Space>
            </>
          ),
        };
        arrs.push(obj);
      }
      setlist(arrs);
    });
  };

  let tagsaxios = async (num: any) => {
    axios.query({ q: num }).then((res) => {
      let arr = res.data;
      // console.log(res.data);
      let arrs = [];
      for (let i = 0; i < arr.length; i++) {
        let obj = {
          key: i,
          username: (
            <>
              <div style={{ float: "left" }}>
                <img src={arr[i].touxiang}></img>
              </div>
              <div style={{ float: "right" }}>
                <div>{arr[i].username}</div>
                <div>{arr[i].tel}</div>
              </div>
            </>
          ),
          viptype:
            arr[i].viptype == 1
              ? "普通会员"
              : arr[i].viptype == 2
              ? "金卡会员"
              : arr[i].viptype == 3
              ? "银卡会员"
              : arr[i].viptype == 4
              ? "白金会员"
              : "钛金会员",
          tags: arr[i].tags,
          orderNum: arr[i].orderNum,
          orderAmount: arr[i].orderAmount,
          state: (
            <Switch
              defaultChecked
              onChange={() => {
                onChangeUser(arr[i].state, arr[i].id);
              }}
              checked={arr[i].state}
            />
          ),
          registerTime: arr[i].registerTime,
          operation: (
            <>
              <Space>
                <Button onClick={()=>{
                  props.history.push("/system/user/userdetail/"+arr[i].id)
                }}>用户详情</Button>
                {/* <Button onClick={()=>{
                  props.history.push("/system/user/useredit/"+arr[i].id)
                }}>编辑用户</Button> */}
                <Button onClick={()=>{
                del(arr[i].id)
              }}>删除</Button>
              </Space>
            </>
          ),
        };
        arrs.push(obj);
      }
      setlist(arrs);
    });
  };

  let initList = async () => {
    axios.query({}).then((res) => {
      let arr = res.data;
      let arrs = [];
      for (let i = 0; i < arr.length; i++) {
        let obj = {
          key: i,
          username: (
            <>
              <div style={{ float: "left" }}>
                <img src={arr[i].touxiang}></img>
              </div>
              <div style={{ float: "right" }}>
                <div>{arr[i].username}</div>
                <div>{arr[i].tel}</div>
              </div>
            </>
          ),
          viptype:
            arr[i].viptype == 1
              ? "普通会员"
              : arr[i].viptype == 2
              ? "金卡会员"
              : arr[i].viptype == 3
              ? "银卡会员"
              : arr[i].viptype == 4
              ? "白金会员"
              : "钛金会员",
          tags: arr[i].tags,
          orderNum: arr[i].orderNum,
          orderAmount: arr[i].orderAmount,
          state: (
            <Switch
              defaultChecked
              onChange={() => {
                onChangeUser(arr[i].state, arr[i].id);
              }}
              checked={arr[i].state}
            />
          ),
          registerTime: arr[i].registerTime,
          operation: (
            <>
              <Space>
                <Button onClick={()=>{
                  props.history.push("/system/user/userdetail/"+arr[i].id)
                }}>用户详情</Button>
                {/* <Button onClick={()=>{
                  props.history.push("/system/user/useredit/"+arr[i].id)
                }}>编辑用户</Button> */}
                <Button onClick={()=>{
                del(arr[i].id)
              }}>删除</Button>
              </Space>
            </>
          ),
        };
        arrs.push(obj);
      }
      setlist(arrs);
    });
  };
  let search = async (value: any) => {
    let res = await axios.query({ q: value });
    console.log(res.data);
    let arr = res.data;
    let arrs = [];
    for (let i = 0; i < arr.length; i++) {
      let obj = {
        key: i,
        username: (
          <>
            <div style={{ float: "left" }}>
              <img src={arr[i].touxiang}></img>
            </div>
            <div style={{ float: "right" }}>
              <div>{arr[i].username}</div>
              <div>{arr[i].tel}</div>
            </div>
          </>
        ),
        viptype:
          arr[i].viptype == 1
            ? "普通会员"
            : arr[i].viptype == 2
            ? "金卡会员"
            : arr[i].viptype == 3
            ? "银卡会员"
            : arr[i].viptype == 4
            ? "白金会员"
            : "钛金会员",
        tags: arr[i].tags,
        orderNum: arr[i].orderNum,
        orderAmount: arr[i].orderAmount,
        state: (
          <Switch
            defaultChecked
            onChange={() => {
              onChangeUser(arr[i].state, arr[i].id);
            }}
            checked={arr[i].state}
          />
        ),
        registerTime: arr[i].registerTime,
        operation: (
          <>
              <Space>
                <Button onClick={()=>{
                  props.history.push("/system/user/userdetail/"+arr[i].id)
                }}>用户详情</Button>
                {/* <Button onClick={()=>{
                  props.history.push("/system/user/useredit/"+arr[i].id)
                }}>编辑用户</Button> */}
                <Button onClick={()=>{
                del(arr[i].id)
              }}>删除</Button>
              </Space>
            </>
        ),
      };
      arrs.push(obj);
    }
    setlist(arrs);
  };
  //日期格式化函数
  function formatTime(date: any) {
    // let dates=new Date().getSeconds;
    var year = date.getFullYear();
    var month = date.getMonth() + 1,
      month = month < 10 ? "0" + month : month;
    var day = date.getDate(),
      day = day < 10 ? "0" + day : day;
    // var hours=date.getHours(),hours=hours<10?'0'+hours:hours;
    // var minutes=date.getMinutes(),minutes=minutes<10?'0'+minutes:minutes;
    // var seconds=date.getSeconds(),seconds=seconds<10?'0'+seconds:seconds;
    return year + "-" + month + "-" + day;
  }
  let date = (value: any) => {
    let now = new Date();
    if (value == 0) {
      let time = formatTime(now);
      console.log(time);
      search(time);
    } else if (value == -1) {
      now.setDate(now.getDate() - 1);
      let time = formatTime(now);
      console.log(time);
      search(time);
    } else if (value == -7) {
      let time1 = formatTime(now);
      now.setDate(now.getDate() - 7);
      let time = formatTime(now);
      console.log(time);
      searchwhere(time, time1);
    } else if (value == -30) {
      let time1 = formatTime(now);
      now.setDate(now.getDate() - 30);
      let time = formatTime(now);
      console.log(time);
      searchwhere(time, time1);
    }
  };
  //条件查询
  let searchwhere = async (value: any, value1: any) => {
    let res = await axios.query({
      registerTime_gte: value,
      registerTime_lte: value1,
    });
    //上架时间大于等于value
    //gte 大于等于
    //lte 小于等于
    console.log(res.data);
    let arr = res.data;
    let arrs = [];
    for (let i = 0; i < arr.length; i++) {
      let obj = {
        key: i,
        username: (
          <>
            <div style={{ float: "left" }}>
              <img src={arr[i].touxiang}></img>
            </div>
            <div style={{ float: "right" }}>
              <div>{arr[i].username}</div>
              <div>{arr[i].tel}</div>
            </div>
          </>
        ),
        viptype:
          arr[i].viptype == 1
            ? "普通会员"
            : arr[i].viptype == 2
            ? "金卡会员"
            : arr[i].viptype == 3
            ? "银卡会员"
            : arr[i].viptype == 4
            ? "白金会员"
            : "钛金会员",
        tags: arr[i].tags,
        orderNum: arr[i].orderNum,
        orderAmount: arr[i].orderAmount,
        state: (
          <Switch
            defaultChecked
            onChange={() => {
              onChangeUser(arr[i].state, arr[i].id);
            }}
            checked={arr[i].state}
          />
        ),
        registerTime: arr[i].registerTime,
        operation: (
          <>
              <Space>
                <Button onClick={()=>{
                  props.history.push("/system/user/userdetail/"+arr[i].id)
                }}>用户详情</Button>
                {/* <Button onClick={()=>{
                  props.history.push("/system/user/useredit/"+arr[i].id)
                }}>编辑用户</Button> */}
                <Button onClick={()=>{
                del(arr[i].id)
              }}>删除</Button>
              </Space>
            </>
        ),
      };
      arrs.push(obj);
    }
    setlist(arrs);
  };

  let [selectedRowKeys, setselectedRowKeys] = useState<any>([]);
  function onChangeUser(checked: any, id: any) {
    let obj = {
      id: id,
      state: !checked,
    };
    axios.patch(obj);
    initList();
  }
  const columns = [
    {
      title: "用户信息",
      dataIndex: "username",
    },
    {
      title: "会员等级",
      dataIndex: "viptype",
    },
    {
      title: "用户标签",
      dataIndex: "tags",
      render: (tags: any) => (
        <span>
          {tags.map((tag: any) => {
            return (
              <Tag color="geekblue" key={tag}>
                {tag}
              </Tag>
            );
          })}
        </span>
      ),
    },
    {
      title: "消费次数",
      dataIndex: "orderNum",
    },
    {
      title: "消费金额",
      dataIndex: "orderAmount",
    },
    {
      title: "用户状态",
      dataIndex: "state",
    },
    {
      title: "注册时间",
      dataIndex: "registerTime",
    },
    {
      title: "操作",
      dataIndex: "operation",
    },
  ];
  const data = list;

  let onSelectChange = (selectedRowKeys: any) => {
    console.log("selectedRowKeys changed: ", selectedRowKeys);
    setselectedRowKeys(selectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: "odd",
        text: "Select Odd Row",
        onSelect: (changableRowKeys: any[]) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((key, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
          setselectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: "even",
        text: "Select Even Row",
        onSelect: (changableRowKeys: any[]) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((key, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
          setselectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  };
  return (
    <div>
      <div
        className="head"
        style={{ backgroundColor: "#fff", padding: "35px" }}
      >
        <p style={{ fontSize: "22px" }}>用户查询</p>
        <hr style={{ marginBottom: "20px" }}></hr>
        <div style={{ float: "left" }}>
          <span style={{ fontSize: "18px" }}>会员等级：</span>
          <Space>
            <Button
              onClick={() => {
                initList();
              }}
            >
              不限
            </Button>
            <Button
              onClick={() => {
                viptypeaxios(1);
              }}
            >
              普通
            </Button>
            <Button
              onClick={() => {
                viptypeaxios(2);
              }}
            >
              金卡
            </Button>
            <Button
              onClick={() => {
                viptypeaxios(3);
              }}
            >
              银卡
            </Button>
            <Button
              onClick={() => {
                viptypeaxios(4);
              }}
            >
              白金
            </Button>
            <Button
              onClick={() => {
                viptypeaxios(5);
              }}
            >
              钛金
            </Button>
          </Space>
        </div>

        <div style={{ clear: "both", marginTop: "70px", fontSize: "18px" }}>
          <span style={{ fontSize: "18px" }}>注册日期：</span>
          <Space direction="vertical" size={12}>
            <RangePicker
              onChange={(value: any) => {
                if (value[0]._d && value[1]._d) {
                  console.log(value[0]._d);
                  console.log(value[1]._d);
                  let date = new Date(value[0]._d);
                  let y = date.getFullYear();
                  let m: any = date.getMonth() + 1;
                  m = m < 10 ? "0" + m : m;
                  let d: any = date.getDate();
                  d = d < 10 ? "0" + d : d;
                  let starttime = y + "-" + m + "-" + d;
                  console.log(starttime);
                  date = new Date(value[1]._d);
                  y = date.getFullYear();
                  m = date.getMonth() + 1;
                  m = m < 10 ? "0" + m : m;
                  d = date.getDate();
                  d = d < 10 ? "0" + d : d;
                  let endtime = y + "-" + m + "-" + d;
                  console.log(endtime);
                  searchwhere(starttime, endtime);
                  // setStartTime(value[0]._d);
                  // setEndTime(value[1]._d);
                }
              }}
            />
          </Space>
          <Button
            style={{ marginLeft: "20px" }}
            onClick={() => {
              date(0);
            }}
          >
            今日
          </Button>
          <Button
            style={{ marginLeft: "20px" }}
            onClick={() => {
              date(-1);
            }}
          >
            昨日
          </Button>
          <Button
            style={{ marginLeft: "20px" }}
            onClick={() => {
              date(-7);
            }}
          >
            最近七天
          </Button>
          <Button
            style={{ marginLeft: "20px" }}
            onClick={() => {
              date(-30);
            }}
          >
            最近30天
          </Button>
          {/* <Button
            style={{ float: "right", marginRight: "80px" }}
            onClick={() => {
              window.location.reload();
            }}
          >
            重置
          </Button>
          <Button
            type="primary"
            style={{ float: "right", marginRight: "20px" }}
            onClick={() => {
              search(keyword);
            }}
          >
            查询
          </Button> */}
        </div>
        <div style={{ marginTop: "20px" }}>
          <span style={{ fontSize: "18px" }}>会员标签：</span>
          <Space>
            <Button
              onClick={() => {
                initList();
              }}
            >
              不限
            </Button>
            <Button
              onClick={() => {
                tagsaxios("标签一");
              }}
            >
              标签一
            </Button>
            <Button
              onClick={() => {
                tagsaxios("标签二");
              }}
            >
              标签二
            </Button>
            <Button
              onClick={() => {
                tagsaxios("标签三");
              }}
            >
              标签三
            </Button>
            <Button
              onClick={() => {
                tagsaxios("标签四");
              }}
            >
              标签四
            </Button>
            <Button
              onClick={() => {
                tagsaxios("标签五");
              }}
            >
              标签五
            </Button>
          </Space>
        </div>
        <div style={{ marginTop: "20px" }}>
          <span style={{ fontSize: "18px" }}>用户查询：</span>
          <Input
            style={{ width: "200px" }}
            placeholder="请输入要搜索的关键词"
            onChange={(e) => {
              setkeywords(e.target.value);
              // console.log(e.target.value)
            }}
          ></Input>
          <Space style={{ float: "right", marginRight: "50px" }}>
            <Button
              type="primary"
              onClick={() => {
                search(keywords);
              }}
            >
              查询
            </Button>
            <Button
              onClick={() => {
                window.location.reload();
              }}
            >
              重置
            </Button>
          </Space>
        </div>
      </div>
      <div
        style={{ backgroundColor: "#fff", padding: "35px", marginTop: "20px" }}
      >
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={data}
        />
      </div>
    </div>
  );
}
